# *-* coding:utf8 *-*
from flask import make_response, session
from info.utils.captcha.captcha import captcha
import random
import re
from info.lib import CCP
from info.models import User
from . import pass_port_blu
from flask import jsonify
from flask import request
from flask import current_app
from info import constants, db
from info import redis_store

from info.utils.response_code import RET

@pass_port_blu.route('/image_code')
def pass_port():
    '''获取图片验证码'''
    # 1.获取到当前图片的编号id
    code_id = request.args.get('code_id')
    print(type(code_id), code_id)
    # 生成
    name,text,image = captcha.generate_captcha()
    print(text)
    try:
        # 保存当前生成的图片验证码的内容
        redis_store.set('ImageCode' + code_id, text,  constants.IMAGE_CODE_REDIS_EXPIRES)

    except Exception as e:
        current_app.logger.error(e)
        return make_response(jsonify(errno=RET.DATAERR,errmsg='保存失败'))

    # 返回内容
    resp = make_response(image)
    resp.headers['Content-Type'] = 'image/jpg'
    return resp



@pass_port_blu.route('/smscode',methods=["POST"])
def send_sms():
    # 取到请求值
    args_data = request.json
    mobile = args_data.get('mobile')
    image_code = args_data.get('image_code')
    # 随机数
    image_code_id = args_data.get('image_code_id')

    # 判断用户输入的参数
    if not all([mobile,image_code_id,image_code]):
        # 参数不全
        return jsonify(errno=RET.PARAMERR,errmsg = '参数不全,重新输入')

    # 验证手机号的正确
    if not re.match('^1[3578][0-9]{9}$',mobile):
        return jsonify(errno=RET.DATAERR,errmsg = '手机号不正确！！！')

    # 通过传入的图片取ｒｅｄｉｓ中查询真实的图片验证码内容
    try:
        real_image_code = redis_store.get('ImageCode' + image_code_id)
        # 如果取出值，就删除ｒｅｄｉｓ缓存
        if real_image_code:
            redis_store.delete('ImageCode' + image_code_id)

    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno = RET.DBERR,errmsg = '获取图片验证码失败')

    # 判断验证码是否存在，过期
    if not real_image_code:
        return jsonify(errno = RET.NODATA,errmsg = '验证码已经过期')

    # 进行验证码对比
    if image_code.lower()!=real_image_code.lower():
        return jsonify(errno = RET.DATAERR,errmsg = '验证码输入错误')

    # 检验手机是否已经注册
    try:
        user = User.query.filter_by(mobile=mobile).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno = RET.DBERR,errmsg = '查询数据库错误')

    if user:
        return jsonify(errno = RET.DATAEXIST,errmsg = '该手机已经被注册')

    # 生成发送短信内容并发送
    result = random.randint(0,9999999)
    sms_code = '%06d' % result
    current_app.logger.debug('短信验证码的内容: {}'.format(sms_code))
    # result = CCP().send_template_sms(mobile, [sms_code, constants.SMS_CODE_REDIS_EXPIRES / 60], "1")
    #if result != 0:
    #    return jsonify(errno = RET.THIRDERR,errmsg = '发送短信失败')

    #　ｒｅｄｉｓ中保存短信验证吗的内容
    try:
        redis_store.set('SMS_' + mobile,sms_code,constants.SMS_CODE_REDIS_EXPIRES)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno = RET.DBERR,errmsg = '保存验证码失败')

    # 返回发送成功的响应
    return jsonify(errno = RET.OK,errmsg = '发送成功')


@pass_port_blu.route('/register',methods=['POST'])
def register():
    '''获取参数'''
    json_data = request.json
    mobile = json_data.get('mobile')
    sms_code = json_data.get('smscode')
    password = json_data.get('password')

    # 判断参数
    if not all([mobile,sms_code,password]):
        return jsonify(errno = RET.PARAMERR,errmsg = '参数不全')


    # 从redis中获取指定手机号对应的短信验证码
    try:
        real_sms_code = redis_store.get('SMS_' + mobile)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='获取失败！！！！')
    # 短信验证码过期
    if not real_sms_code:
        return jsonify(errno=RET.NODATA, errmsg='验证码已经过期')

    # 校验验证码
    if sms_code != real_sms_code:
        return jsonify(errno = RET.DATAERR,errmsg = '验证码不正确！！')

    # 删除短信验证码
    try:
        redis_store.delete('SMS' + mobile)

    except Exception as e:
        current_app.logger.error(e)

    # 初始化user模型
    user = User()
    user.nick_name = mobile
    user.mobile = mobile
    user.password = password
    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno = RET.DATAERR,errmsg = '保存数据错误')

    session['user_id'] = user.id
    session['user_name'] = user.nick_name
    session['mobile'] = user.mobile

    return jsonify(errno = RET.OK,errmsg = 'OK')

@pass_port_blu.route('/login', methods=['POST'])
def login():
    '''登陆'''
    # 获取参数和判断是否有值
    json_data = request.json
    mobile = json_data.get('mobile')
    password = json_data.get('password')

    if not all([mobile,pass_port_blu]):
        return jsonify(errno = RET.PARAMERR,errmsg = '参数错误')
    # 从数据库查询出指定的用户
    try:
        user = User.query.filter_by(mobile = mobile).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno = RET.DBERR,errmsg = '查询数据库错误')
    if not user:
        return jsonify(errno = RET.USERERR,errmsg = '用户不存在')


    # 校验密码
    if not user.check_passowrd(password):
        return jsonify(errno = RET.PWDERR,errmsg = '密码错误')

    # 保存用户登录状态
    session['user_id'] = user.id
    session['nick_name'] = user.nick_name
    session['user_mobile'] = user.mobile
    from datetime import datetime
    user.last_login = datetime.now()
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)

    # 返回结果
    return jsonify(errno = RET.OK,errmsg = 'OK')


@pass_port_blu.route('/logout',methods=['POST'])
def logout():
    '''退出功能'''
    session.pop('user_id',None)
    session.pop('nick_name',None)
    session.pop('mobile',None)
    session.pop('is_admin',None)

    return jsonify(errno = RET.OK,errmsg = 'OK')